<template>
  <el-dialog
    :close-on-click-modal="false"
    title="招标限价"
    :visible.sync="show"
    width="1000px"
    center
  >
    <el-form ref="form" :rules="rules" style="padding-top: 10px;" :model="form" label-width="100px">
      <div class="com-form-title">基本信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="招标编号" prop="bidNumber">
            <!-- <el-input v-model="form.bidNumber" :disabled="disableForm" /> -->
            <el-input v-model="form.bidNumber" readonly :disabled="disableForm || optType !== 'add'" @click.native="optType === 'add' ? showListModal = true : null">
              <i slot="suffix" class="el-input__icon el-icon-circle-plus-outline" />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="招标名称" prop="bidName">
            <el-input v-model="form.bidName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="招标机构" prop="bidOrganization">
            <el-input v-model="form.bidOrganization" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="招标方式" prop="bidMode">
            <el-select v-model="form.bidMode" disabled style="width: 100%;" placeholder="请选择招标方式">
              <el-option v-for="item in bidLimitInfoBidMode" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="招标类型" prop="bidType">
            <el-select v-model="form.bidType" disabled style="width: 100%;" placeholder="请选择招标类型">
              <el-option v-for="item in bidLimitInfoBidType" :key="item.name" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="限价总额(元)" prop="basLimitPrice">
            <el-input v-model="form.basLimitPrice" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="basRemark">
            <el-input v-model="form.basRemark" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px;">
        <el-button type="primary" @click="addRow">新增行</el-button>
        <el-button type="primary" @click="deleteDetail">删除行</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:number="{row}">
          <el-input v-model="row.number" />
        </template>
        <template v-slot:name="{row}">
          <el-input v-model="row.name" />
        </template>
        <template v-slot:specification="{row}">
          <el-input v-model="row.specification" />
        </template>
        <template v-slot:unit="{row}">
          <el-input v-model="row.unit" />
        </template>
        <template v-slot:limitPrice="{row}">
          <el-input v-model="row.limitPrice" @input="inputLimitPrice" />
        </template>
        <template v-slot:count="{row}">
          <el-input v-model="row.count" @input="inputLimitPrice" />
        </template>
        <template v-slot:sum="{row}">
          <el-input v-model="row.sum" />
        </template>
        <template v-slot:description="{row}">
          <el-input v-model="row.description" />
        </template>
        <template v-slot:area="{row}">
          <el-input v-model="row.area" />
        </template>
        <template v-slot:remark="{row}">
          <el-input v-model="row.remark" />
        </template>
        <template v-slot:payOrRent="{row}">
          <el-input v-model="row.payOrRent" />
        </template>
        <template v-slot:rentRange="{row}">
          <el-input v-model="row.rentRange" />
        </template>
        <template v-slot:options="{row}">
          <el-button size="mini" type="danger" @click="delRow(row)">删除</el-button>
        </template>

      </com-table>
      <el-button style="margin-top:10px;" type="primary" @click="showFileModal = true">附件资料({{ fileList.length }})</el-button>
      <file-uploader v-model="fileList" :show-modal.sync="showFileModal" :disabled="disableForm" :can-download="optType==='detail'" />

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="show = false">取 消</el-button>
      <el-button type="primary" @click="saveDoc">确 定</el-button>
    </span>
    <listSelect :show-modal.sync="showListModal" title="招标信息选择" :columns="listColumns" :api="getBidFinishInfoList" @getSelectedData="getSelectedRows" />
  </el-dialog>
</template>

<script>
import { addBidLimitInfo, updateBidLimitInfo, getBidLimitInfoDetail, getBidFinishInfoList } from '@/api/bigManage'
import { getAreaList } from '@/api/common'
import { getDictValue } from '@/utils/comm'
import { bidLimitInfoBidMode, bidLimitInfoBidType, workflowStatus } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import listSelect from '@/components/ListSelect'
export default {
  name: 'AddBidLimitInfo',
  components: {
    fileUploader,
    listSelect
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getBidFinishInfoList,
      showFileModal: false,
      showListModal: false,
      selectRow: null,
      targetList: [],
      bidLimitInfoBidMode,
      bidLimitInfoBidType,
      workflowStatus,
      getDictValue,
      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        bidInfoId: '',
        bidOrganization: '',
        bidNumber: '',
        bidName: '',
        bidMode: '',
        bidType: '',
        basLimitPrice: '',
        basRemark: '',
        addWorkflowId: '',
        status: '',
        createTime: ''
      },
      listColumns: [
        {
          label: '招标机构',
          prop: 'organization'
        },
        {
          label: '招标编号',
          prop: 'number',
          width: '180'
        },
        {
          label: '招标名称',
          prop: 'name',
          width: '150'
        },
        {
          label: '招标方式',
          prop: 'mode'
        },
        {
          label: '招标类型',
          prop: 'type'
        },
        {
          label: '报名开始时间',
          prop: 'applyStartTime',
          width: '100'
        },
        {
          label: '报名结束时间',
          prop: 'applyEndTime',
          width: '100'
        },
        {
          label: '报价开始时间',
          prop: 'quotationStartTime',
          width: '100'
        },
        {
          label: '报价结束时间',
          prop: 'quotationEndTime',
          width: '100'
        },
        {
          label: '开标时间',
          prop: 'bidStartTime',
          width: '100'
        },
        {
          label: '开标地点',
          prop: 'bidAddress'
        },
        {
          label: '联系人',
          prop: 'contactPerson'
        },
        {
          label: '联系电话',
          prop: 'contactPhone'
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '编制时间',
          prop: 'createTime',
          width: '90'
        }
      ],
      columns: [
        {
          label: '编号',
          slot: 'number'
        },
        {
          label: '名称',
          slot: 'name',
          width: '150'
        },
        {
          label: '规格',
          slot: 'specification',
          width: '150'
        },
        {
          label: '单位',
          slot: 'unit',
          width: '150'
        },
        {
          label: '限价(元)',
          slot: 'limitPrice',
          width: '150'
        },
        {
          label: '数量',
          slot: 'count',
          width: '150'
        },
        {
          label: '合价',
          slot: 'sum',
          width: '150'
        },
        {
          label: '描述',
          slot: 'description',
          width: '150'
        },
        {
          label: '区域',
          slot: 'area',
          width: '150'
        },
        {
          label: '备注',
          slot: 'remark',
          width: '150'
        },
        {
          label: '采购/租赁',
          slot: 'payOrRent'
        },
        {
          label: '租赁时间段',
          slot: 'rentRange',
          width: '200'
        },
        {
          fixed: 'right',
          label: '操作',
          width: '100',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      fileList: [
      ],
      rules: {
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    showModal(val) {
      if (val && this.optType !== 'add') {
        this.getDocDetail(this.data.id)
        this.$nextTick(() => {
          Object.keys(this.form).forEach(key => {
            const source = this.data[key]
            if (typeof source === 'boolean') {
              this.form[key] = source ? 1 : 0
            } else {
              this.form[key] = source
            }
          })
        })
      } else if (!val) {
        this.fileList = []
        this.targetList = []
        this.$refs.form.resetFields()
      }
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    addRow() {
      this.targetList = [
        ...this.targetList,
        {
          number: '',
          name: '',
          specification: '',
          unit: '',
          limitPrice: '',
          count: '',
          sum: '',
          description: '',
          area: '',
          remark: '',
          payOrRent: '',
          rentRange: ''
        }
      ]
    },
    delRow(row) {
      this.$confirm('确定要删除该数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.targetList.indexOf(row)
        if (index > -1) {
          this.targetList.splice(index, 1)
        }
      }).catch(() => {
      })
    },
    getSelectedRows(data) {
      if (data) {
        // this.supplierInfo = data
        const { name, number, organization, mode, type, id } = data
        this.form.bidInfoId = id
        this.form.bidName = name
        this.form.bidNumber = number
        this.form.bidOrganization = organization
        this.form.bidMode = this.getDictValue(this.bidLimitInfoBidMode, mode)
        this.form.bidType = this.getDictValue(this.bidLimitInfoBidType, type)
      }
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter(val => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then(res => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getBidLimitInfoDetail({ bidLimitInfoId: id }).then(res => {
        const { lstAttachment, lstBidLimitDetail } = res.data || {}
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (lstBidLimitDetail && lstBidLimitDetail.length > 0) {
          this.targetList = lstBidLimitDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then(res => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {
    },
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const params = {
            bidLimitInfo: {
              ...this.form,
              ...this.optType === 'edit' ? {
                id: this.data.id
              } : {}
            },
            lstBidLimitDetail: this.targetList.map(item => {
              return {
                ...item,
                ...this.optType === 'edit' ? {
                  bidLimitInfoId: this.data.id
                } : {}
              }
            }),
            lstAttachment: this.fileList
          }
          const fn = this.optType === 'add' ? addBidLimitInfo : updateBidLimitInfo
          fn(params).then(res => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    // 获取限价总额
    getLimitSumPrice() {
      let sum = 0
      this.targetList.forEach(item => {
        if (item.sum) {
          sum += Number.parseFloat(item.sum)
        }
      })
      this.form.basLimitPrice = sum.toFixed(2)
    },
    // 计算限价*数量=合价
    inputLimitPrice() {
      // 获取当前行合价
      let limitPrice = 0
      let count = 0
      if (this.selectRow.limitPrice) {
        limitPrice = this.selectRow.limitPrice
      }
      if (this.selectRow.count) {
        count = this.selectRow.count
      }
      const sumPrice = Number.parseFloat(limitPrice) * Number.parseFloat(count)
      this.selectRow.sum = sumPrice.toFixed(2)
      // 获取限价总额
      this.getLimitSumPrice()
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}
</style>
